package com.foruo.learn.designmode.singleton;

/**
 * 单例 - 懒汉式（即类加载时没有实例化，调用取得实例的方法getInstance()的时候才实例化对象）
 * @author GaoYuan
 * @date 2018/5/4 上午8:09
 */
public class SingletonDemoEntity2 {
    /** 注意 static 并且没有初始化 */
    private static SingletonDemoEntity2 singletonDemoEntity;

    /** 注意 private */
    private SingletonDemoEntity2(){}

    /** 注意 synchronized */
    public static synchronized SingletonDemoEntity2 getInstance(){
        if(singletonDemoEntity == null){
            singletonDemoEntity = new SingletonDemoEntity2();
        }
        return singletonDemoEntity;
    }


    public static void main(String[] args){
        MyThread2 myThread = new MyThread2();

        Thread thread1 = new Thread(myThread);
        Thread thread2 = new Thread(myThread);
        Thread thread3 = new Thread(myThread);

        thread1.start();
        thread2.start();
        thread3.start();

        //此处可见三次打印相同内容，则表示是同一个对象
    }


}

class MyThread2 extends Thread{

    @Override
    public void run() {
        System.out.println(SingletonDemoEntity2.getInstance().hashCode());
    }

}
